package com.example.network.slice;

import com.example.network.ResourceTable;
import com.example.network.Utils;
import com.example.network.WebViewAbility;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONObject;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Button mBtnGetString;
    private Button mBtnGetPixelmap;
    private Button mBtnGetByOkhttp;
    private Button mBtnPostByOkhttp;
    private Button mBtnWebview;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mBtnGetString = (Button) findComponentById(ResourceTable.Id_btn_get_string);
        mBtnGetString.setClickedListener(this);
        mBtnGetPixelmap = (Button) findComponentById(ResourceTable.Id_btn_get_pixelmap);
        mBtnGetPixelmap.setClickedListener(this);
        mBtnGetByOkhttp = (Button) findComponentById(ResourceTable.Id_btn_get_by_okhttp);
        mBtnGetByOkhttp.setClickedListener(this);
        mBtnPostByOkhttp = (Button) findComponentById(ResourceTable.Id_btn_post_by_okhttp);
        mBtnPostByOkhttp.setClickedListener(this);
        mBtnWebview = (Button) findComponentById(ResourceTable.Id_btn_webview);
        mBtnWebview.setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {
        // 通过HTTP获取文本
        if (component.getId() == ResourceTable.Id_btn_get_string) {
            // 分发到非主线程
            getGlobalTaskDispatcher(
                    TaskPriority.DEFAULT).asyncDispatch(() -> {
                // 声明Reader对象
                BufferedReader reader = null;
                try {
                    //打开URL连接
                    URL url = new URL("http://192.168.0.10/test.json");
                    URLConnection connection = url.openConnection();
                    // 通过数据流获取其文本数据
                    InputStream inputStream = connection.getInputStream();
                    reader = new BufferedReader(
                            new InputStreamReader(inputStream));
                    String jsonStr = ""; // 结果数据
                    String line; // 行数据
                    while ((line = reader.readLine())!= null) {
                        jsonStr += line;
                    }
                    // jsonStr数据读取完成，获取JSON数组
                    ZSONArray students = ZSONArray.stringToZSONArray(jsonStr);
                    // 遍历数组中的每一个对象
                    for (int i = 0; i < students.size(); i ++) {
                        // 获取对象
                        ZSONObject student = students.getZSONObject(i);
                        // 打印对象信息
                        Utils.log("姓名: " + student.getString("name")
                                + " 年龄: " + student.getInteger("age")
                                + " 性别: " + student.getInteger("sex")
                                + " 班级: " + student.getString("class"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 关闭Reader对象
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        // 通过HTTP获取图片
        if (component.getId() == ResourceTable.Id_btn_get_pixelmap) {
            // 分发到非主线程
            getGlobalTaskDispatcher(
                    TaskPriority.DEFAULT).asyncDispatch(() -> {
                // 声明InputStream对象
                InputStream inputStream = null;
                try {
                    //打开URL连接
                    URL url = new URL("http://192.168.0.10/image.png");
                    URLConnection connection = url.openConnection();
                    connection.setConnectTimeout(5*1000); // 超时时间
                    // 通过数据流获取其图片数据
                    inputStream = connection.getInputStream();
                    // 通过数据流创建Image源
                    ImageSource source = ImageSource.create(inputStream,
                            new ImageSource.SourceOptions());
                    // 解码选项
                    ImageSource.DecodingOptions options =
                            new ImageSource.DecodingOptions();
                    // 解析为pixelMap
                    PixelMap pixelMap = source.createPixelmap(options);
                    Utils.log("图像宽度: " +  pixelMap.getImageInfo().size.width
                            + " 图像高度: " +  pixelMap.getImageInfo().size.height);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 关闭InputStream对象
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        // 通过okhttp进行GET请求
        if (component.getId() == ResourceTable.Id_btn_get_by_okhttp) {
            getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(()-> {
                // 创建OkHttpClient对象
                OkHttpClient client = new OkHttpClient();
                // 创建请求对象
                Request request = new Request.Builder()
                        .url("http://192.168.0.10/test.json")
                        .build();
                // 获取结果数据
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    // 打印结果数据
                    String output = response.body().string();
                    Utils.log(output);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    // 关闭response对象
                    if (response!=null) {
                        response.close();
                    }
                }
            });
        }
        // 通过okhttp进行POST请求
        if (component.getId() == ResourceTable.Id_btn_post_by_okhttp) {
            getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(()-> {
                // 创建OkHttpClient对象
                // 创建OkHttpClient对象
                OkHttpClient client = new OkHttpClient();
                // 创建FormBody，添加POST请求信息
                FormBody body = new FormBody.Builder()
                        .add("username", "dongyu")
                        .add("password", "dy123456")
                        .build();
                // 创建请求对象
                Request request = new Request.Builder()
                        .url("http://192.168.0.10/test.json")
                        .post(body)
                        .build();
                // 获取结果数据
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    // 打印结果数据
                    String output = response.body().string();
                    Utils.log(output);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    // 关闭response对象
                    if (response!=null) {
                        response.close();
                    }
                }
            });
        }
        // WebView
        if (component.getId() == ResourceTable.Id_btn_webview) {
            // 启动RdbAbility
            startAbility(Utils.generatePageNavigationIntent(WebViewAbility.class.getName()));
        }
    }
}
